<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta http-equiv="X-UA-Compatible" content="IE=edge">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Document</title>
  <style>
    #canvas {
      box-shadow: 2px 4px 6px #eee;
    }
  </style>
</head>
<body>
  <canvas id="canvas"></canvas>
</body>
<script src="../script/utils.js"></script>
<script src="../components/Ball.js"></script> 
<script>
  const canvas = document.getElementById('canvas')
  const ctx = canvas.getContext('2d')
  
  const W = canvas.width = 800
  const H = canvas.height = 600
  
  let mouse = C.getOffset(canvas)
  let spring = 0.05
  let friction = 0.95
  let springLength = 200
  let balls = []
  let draggedBall = null

  for (let i = 0; i < 6; i++) {
    balls.push(new Ball({
      x: C.rp([50, W - 50]),
      y: C.rp([50, H - 50]),
      r: 20
    }))
  }

  canvas.addEventListener('mousedown', function (e) {
    e.preventDefault()
    for (const itemBall of balls) {
      if (itemBall.isPoint(mouse)) {
        itemBall.dragged = true
        draggedBall = itemBall
      }
    }
  })
  canvas.addEventListener('mousemove', function (e) {
    if (draggedBall) {
      draggedBall.x = mouse.x
      draggedBall.y = mouse.y
    }
  })
  canvas.addEventListener('mouseup', function (e) {
    draggedBall.dragged = false
    draggedBall = null
  })

  function springTo(b1, b2) {
    let dx = b2.x - b1.x
    let dy = b2.y - b1.y
    let angle = Math.atan2(dy, dx)
    let targetX = b2.x - Math.cos(angle) * springLength
    let targetY = b2.y - Math.sin(angle) * springLength

    b1.vx += (targetX - b1.x) * spring
    b1.vy += (targetY - b1.y) * spring
    b1.vx *= friction
    b1.vy *= friction

    b1.x += b1.vx
    b1.y += b1.vy
  }

  function drawFrame() {
    window.requestAnimationFrame(drawFrame)
    ctx.clearRect(0, 0, W, H)

    ctx.beginPath()
    ctx.lineWidth = 2
    ctx.strokeStyle = 'rgb(238, 58, 166)'
    for (const itemBall of balls) {
      ctx.lineTo(itemBall.x, itemBall.y)
    }
    ctx.closePath()
    ctx.stroke()

    balls.forEach((item, i) => {
      if (!item.dragged) {
        let arrTemp = balls.slice()
        arrTemp.splice(i, 1)
        for (const itemBall of arrTemp) {
          springTo(item, itemBall)
        }
      }
      item.render(ctx)
    })
  }
  drawFrame()
</script>
</html>